import 'package:flutter/material.dart';
import 'package:flutter_demo/chapter7-FunctionWidget/inherted-Widget/ShareDataWidget.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: const Text("Function Widget Demo"),
      ),
      body: InheritedWidget(),
    ),
  ));
}

class InheritedWidget extends StatefulWidget {
  @override
  _InheritedWidgetState createState() {
    return _InheritedWidgetState();
  }
}

class _InheritedWidgetState extends State<InheritedWidget> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ShareDataWidget(
        data: count,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(bottom: 20.0),
              child: ShareDataInheritedWidget(),
            ),
            ElevatedButton(
              onPressed: () => setState(() => ++count),
              child: const Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }
}

class ShareDataInheritedWidget extends StatefulWidget {
  @override
  _ShareDataInheritedWidgetState createState() =>
      _ShareDataInheritedWidgetState();
}

class _ShareDataInheritedWidgetState extends State<ShareDataInheritedWidget> {
  @override
  Widget build(BuildContext context) {
    //使用InheritedWidget中的共享数据
    return Text(ShareDataWidget.of(context)!.data.toString());
  }

  @override //下文会详细介绍。
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    print("Dependencies change");
  }
}
